package org.friping.mytool.views;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.ListView;
import android.widget.TextView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.friping.mytool.R;
import org.friping.mytool.dao.UnitDao;
import org.friping.mytool.entity.Unit;
import org.friping.mytool.helper.ActivityHelper;
import org.friping.mytool.helper.Constants;
import org.friping.mytool.views.custom.adapter.DeleteAdapter;

import java.util.List;
import java.util.Map;

@EActivity(R.layout.a_unit_search)
public class UnitSearchActivity extends AppCompatActivity {

    @ViewById
    Toolbar toolbar;

    @ViewById
    ListView listView;

    @ViewById
    TextView btnEdit;

    @Bean
    ActivityHelper activityHelper;

    @Bean
    DeleteAdapter listViewAdapter;

    @Bean
    UnitDao unitDao;

    Integer selectPos = -1;

    @AfterViews
    public void afterView(){
        setSupportActionBar(toolbar);
        initListView();
    }

    @Click(R.id.btnEdit)
    public void toggleEdit(){
        listViewAdapter.setShowDelete(!listViewAdapter.isShowDelete());
        btnEdit.setText(listViewAdapter.isShowDelete() ? R.string.back : R.string.edit);
    }

    @ItemClick
    public void listViewItemClicked(int position){
        Map itemObj = (Map) listViewAdapter.getItem(position);
        Long id = (Long) itemObj.get("id");
        Intent intent = activityHelper.buildIntent(this, UnitEditActivity_.class);
        intent.putExtra("unitId", id);
        selectPos = position;
        this.startActivityForResult(intent, Constants.EDIT_UNIT_REQUEST_CODE);
    }


    @OnActivityResult(Constants.EDIT_UNIT_REQUEST_CODE)
    void onResult(int resultCode, Intent data) {
        switch (resultCode) {
            case Constants.EDIT_UNIT_RESULT_CODE:
            if(selectPos > -1){
                Map item = (Map) listViewAdapter.getItem(selectPos);
                item.put("name", data.getStringExtra("name"));
                listViewAdapter.notifyDataSetChanged();
            }
        }
        selectPos = -1;
    }


    private void initListView() {
        List units = unitDao.listWithMap(Unit.class);

        listViewAdapter.refresh((List<Map>) units);
        listViewAdapter.setDeleteCallback(pos -> {
            Map itemData = (Map) listViewAdapter.getItem(pos);
            unitDao.delete(Unit.class, (Long) itemData.get("id"));
        });
        listView.setAdapter(listViewAdapter);

    }
}
